package com.atguigu.GlobalExceptionHandler;

import com.atguigu.Utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;


import java.sql.SQLIntegrityConstraintViolationException;


@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class ExceptionHandler {
    /**
     * 该异常处理器没有添加
     * 当数据库规定某个字段唯一时，字段再次添加或修改为同样的数据，就会出现捕捉该异常，并提示客户端 “···已存在”
     * @param ex
     * @return
     */
    @org.springframework.web.bind.annotation.ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R exceptionHandler(SQLIntegrityConstraintViolationException ex){
      log.error(ex.getMessage());
        if (ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            log.error(ex.getMessage());
            String message = split[2]+"已存在";
            return R.error(message);
        }
        return R.error("未知错误");
    }

    @org.springframework.web.bind.annotation.ExceptionHandler(CustomException.class)
    public R exceptionHandler(CustomException ex){
        log.error(ex.getMessage());
        return R.error(ex.getMessage());
    }
}
